/*
  How to use
  
  - add this webfont:
  "><script src="https://ax.minicg.com/axhub-pwd.js" pwd="ENCRYPTED_CODE"></script><link href="

  - use this to get ENCRYPTED_CODE:
  http://jsrun.net/q2VKp
*/

(function () {

  let pwdName = 'AXLIB_PWD';

  main();

  function main() {
    hideContents();

    loadJS('https://ax.minicg.com/axloader.js', () => {
      yepnope({
        load: [
          'https://cdn.bootcdn.net/ajax/libs/crypto-js/4.0.0/crypto-js.min.js',
          'https://cdn.bootcdn.net/ajax/libs/sweetalert/2.1.2/sweetalert.min.js',
        ],
        complete: inited
      });
    });
  }

  function inited() {
    // console.log(CryptoJS.SHA1('').toString());

    let pwd = 'da39a3ee5e6b4b0d3255bfef95601890afd80709'; // 默认空密码
    
    let scripts = document.querySelectorAll('script');
    for (let i=0; i<scripts.length; i++) {
      let s = scripts[i];
      let crypted = s.getAttribute('pwd');
      if (crypted) {
        pwd = crypted;
      }
    }

    if (!localStorage.getItem(pwdName)) {
      checkPwd(pwd);
    } else {
      showContents();
    }
  }

  function insertCssRules(cssRules) {
    let style = document.createElement('style');
    let cssText = document.createTextNode(cssRules);

    style.setAttribute('type', 'text/css');
    style.appendChild(cssText);
    document.getElementsByTagName('head')[0].appendChild(style);
  }

  function hideContents() {
    insertCssRules(`#base { visibility: hidden; display: none; opacity: 0; }`);
    top.document.getElementById('sitemapTreeContainer').setAttribute('style', 'visibility: hidden; display: none; opacity: 0;');
  }

  function showContents() {
    document.getElementById('base').setAttribute('style', 'visibility: visible; display: block; opacity: 1;');
    top.document.getElementById('sitemapTreeContainer').setAttribute('style', 'visibility: visible; display: block; opacity: 1;');
  }

  function checkPwd(pwd) {
    swal({
      content: {
        element: "input",
        attributes: { placeholder: "请输入访问密码", type: "password", }
      },
      closeOnClickOutside: false,
    }).then(value => {
      let userPwd = value;
      if (CryptoJS.SHA1(userPwd).toString() == pwd) {
        localStorage.setItem(pwdName, pwd);
        showContents();
      } else {
        swal("无法访问", "你输入了错误的密码！", "error").then(()=>{
          checkPwd(pwd);
        });
      }
    });
  }

  function loadJS(url, callback) {
    var s = document.createElement('script');
    s.onload = callback || function () {
      console.log(url + ' loaded.')
    };
    s.setAttribute('src', url);
    document.querySelector('head').appendChild(s);
  }
}());